package com.xiaoma.fitz.service;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dexcoder.commons.pager.Pager;
import com.dexcoder.dal.JdbcDao;
import com.dexcoder.dal.build.Criteria;
import com.dexcoder.dal.spring.page.PageControl;
import com.xiaoma.fitz.domain.Company;
import com.xiaoma.fitz.dto.QueryCompanyParams;

@Service
public class CompanyService {

    @Autowired
    private JdbcDao jdbcDao;
    
    public Pager findAll(int currentPage, int itemsPerPage) {
        PageControl.performPage(currentPage, itemsPerPage);
        jdbcDao.queryList(new Company());
        return PageControl.getPager();
        
    }
    
    public Pager findCompanys(QueryCompanyParams params) {
    	PageControl.performPage(params.getiDisplayStart()/params.getiDisplayLength() + 1, params.getiDisplayLength());
    	Criteria c = Criteria.select(Company.class);
    	if (StringUtils.isNotBlank(params.getName())) {
    		String name = "%" + params.getName().trim() + "%";
    		c.and("name","like", new Object[]{name});
    	}
    	if (StringUtils.isNotBlank(params.getAddress())) {
    		c.and("address", new Object[]{params.getAddress()});
    	}
    	c.desc("id");
    	jdbcDao.queryList(c);
    	return PageControl.getPager();
    }
    
    public void save(Company company) {
    	company.setCreatedAt(new Date());
        jdbcDao.save(company);
    }
    
    public void delete(long id) {
        jdbcDao.delete(Company.class, id);
    }
    
    public void update(Company company) {
        jdbcDao.update(company);
    }
    
    public Company getById(long id) {
        return jdbcDao.get(Company.class, id);
    }
}
